package com.gitee.fastmybatis.core.ext.transaction;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;

public class AliasTransactionTemplate extends TransactionTemplate {
    private static final long serialVersionUID = -3910002922483473840L;

    private final String dbAlias;

    public AliasTransactionTemplate(String dbAlias, PlatformTransactionManager transactionManager) {
        super(transactionManager);
        this.dbAlias = dbAlias;
    }

    public String getDbAlias() {
        return dbAlias;
    }

    public void rollbackOnException(TransactionStatus status, Throwable ex) throws TransactionException {
        PlatformTransactionManager transactionManager = this.getTransactionManager();
        Assert.state(transactionManager != null, "No PlatformTransactionManager set");
        this.logger.debug("Initiating transaction rollback on application exception", ex);

        try {
            transactionManager.rollback(status);
        } catch (TransactionSystemException ex2) {
            this.logger.error("Application exception overridden by rollback exception", ex);
            ex2.initApplicationException(ex);
            throw ex2;
        } catch (Error | RuntimeException ex2) {
            this.logger.error("Application exception overridden by rollback exception", ex);
            throw ex2;
        }
    }

    public TransactionStatus getTransaction() throws TransactionException {
        return getTransactionManager().getTransaction(this);
    }

}
